#!/usr/bin/python
import sys
import os
import numpy as np

# parameters.
contig_size_file = sys.argv[1]
pileup_single_file = sys.argv[2]

# read in contigs with repeats.
centro = {}
fin = open(sys.argv[3],"rb")
for line in fin:
	centro[line.strip()] = True
fin.close()

# Read in contig sizes.
print "reading contig sizes."
fin = open(contig_size_file, "rb")
lines = fin.readlines()
fin.close()

ctg_sizes = {}
for line in lines:
	tmp = line.strip().split()
	ctg_sizes[tmp[0]] = int(tmp[1])
del lines

# Build numpy arrays for each contig.
ctg_profiles = {}

# read in data.
print "reading single data."
fin = open(pileup_single_file, "rb")
lines = fin.readlines()
fin.close()

cnt = 0
for line in lines:
	cnt += 1
	#if cnt > 1000000: break
	
	# tokenize.
	tmp = line.split()
	ctg = tmp[0]
	idx = int(tmp[1]) - 1
	cov = float(tmp[2])
	
	# check existance.
	if ctg not in ctg_profiles:
		tmp1 = np.zeros(ctg_sizes[ctg], dtype=np.float)
		ctg_profiles[ctg] = tmp1
		
	# add coverage.
	ctg_profiles[ctg][idx] = cov
del lines

# calc average centro.
c_avg = 0.0
c_tot = 0.0
for ctg in centro:
	c_tot += 1.0
	if ctg not in ctg_profiles: continue
	
	# get avg.
	tot = 0
	for i in range(len(ctg_profiles[ctg])):
		tot += ctg_profiles[ctg][i]
	
	avg = float(tot) / float(len(ctg_profiles[ctg]))
	c_avg += avg
	
	
	# remove from profiles.
	del ctg_profiles[ctg]
c_avg = c_avg / c_tot


# calc the other avg.
o_avg = 0.0
o_tot = 0.0
for ctg in ctg_profiles:
	o_tot += 1.0
	if ctg not in ctg_profiles: continue
	
	# get avg.
	tot = 0
	for i in range(len(ctg_profiles[ctg])):
		tot += ctg_profiles[ctg][i]
	
	avg = float(tot) / float(len(ctg_profiles[ctg]))
	o_avg += avg
	
o_avg = o_avg / o_tot

print "centromere avg: %f" % c_avg
print "other avg: %f" % o_avg
